<template>
  <div class="attr">
    <el-card style="margin-bottom: 20px">
      <Category></Category>
    </el-card>
    <el-card v-if="!addAttrFlag">
      <el-button
        type="primary"
        icon="Plus"
        :disabled="categoryStore.category3Id ? false : true"
        @click="addPlatformAttr"
        v-has="`btn.Atrr.add`"
        >添加平台属性</el-button
      >
      <el-table
        border
        style="margin-top: 20px"
        :data="categoryStore.attrInfoList"
      >
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row }">
            <el-tag
              v-for="item in row.attrValueList"
              :key="item.id"
              style="margin: 5px"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row }">
            <el-button
              type="warning"
              icon="Edit"
              @click="editAttr(row)"
            ></el-button>
            <el-popconfirm
              width="220"
              confirm-button-text="确认"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确认要删除该属性吗?"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card v-if="addAttrFlag">
      <el-form>
        <el-form-item label="属性名称">
          <el-input
            style="margin-bottom: 10px; width: 200px"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        icon="Plus"
        type="primary"
        :disabled="attrParams.attrName ? false : true"
        @click="addAttrValue"
        >添加属性值</el-button
      >
      <el-button>取消</el-button>
      <el-table
        border
        style="margin: 10px 0px"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          label="序号"
          type="index"
          width="80px"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #="{ row, $index }">
            <el-input
              v-if="row.flag"
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-model="row.valueName"
              @blur="toLook(row, $index)"
              placeholder="请输入属性值名称"
            ></el-input>
            <pre v-else @click="toEdit(row, $index)">{{ row.valueName }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              icon="Delete"
              @click="deleteAttrValue(row, $index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="saveAttrInfo">保存</el-button>
      <el-button @click="cancelAddAttr">取消</el-button>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import {
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  onDeactivated,
  onActivated,
} from 'vue'
import useCategoryStore from '@/store/modules/category'
import { delAttrItem, saveAttrInfoAPI } from '@/api/product/attr/index.ts'
import { Attr, AttrValue } from '@/api/product/attr/type.ts'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

let categoryStore = useCategoryStore()
let addAttrFlag = ref(false)
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', //新增的属性的名字
  attrValueList: [], //新增的属性值的数组
  categoryId: '', //三级分类的id
  categoryLevel: 3, //三级分类，默认传3
})
let inputArr = ref([])
// 调用接口获取一级分类菜单
const getC1List = async () => {
  try {
    await categoryStore.getC1List()
  } catch (error) {
    console.log(error)
  }
}
// 编辑属性
const editAttr = (row) => {
  addAttrFlag.value = true
  // 将编辑的数据进行回显,注意这里需要通过json.parse对当前对象进行转换，
  // 要不然的话他是一个浅拷贝对象，采用的是地址的引用，要将其转换成深拷贝，这样才不会影响外面的元素
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 删除属性
const deleteAttr = async (id) => {
  console.log(id, '删除')
  let result = await delAttrItem(id)
  const { code } = result
  if (code == 200) {
    ElMessage.success('删除属性成功')
    // 重新请求列表数据
    categoryStore.getAttrInfoList(
      categoryStore.category1Id,
      categoryStore.category2Id,
      categoryStore.category3Id
    )
  }
}
// 添加平台属性按钮点击事件
const addPlatformAttr = () => {
  addAttrFlag.value = !addAttrFlag.value
  // 重置表单元素
  Object.assign(attrParams, {
    attrName: '', //新增的属性的名字
    attrValueList: [], //新增的属性值的数组
    categoryId: categoryStore.category3Id, //三级分类的id
    categoryLevel: 3, //三级分类，默认传3
  })
}
// 编辑或新建属性的保存按钮
const saveAttrInfo = async () => {
  // 如果新建的属性的属性名或属性值为空，那么不允许保存
  if (attrParams.attrName == '' || attrParams.attrValueList.length <= 0) {
    ElMessage.warning('属性名或属性值不允许为空')
    return
  }
  // 调用接口保存新增的属性值
  let result = await saveAttrInfoAPI(attrParams)
  const { code } = result
  if (code == 200) {
    addAttrFlag.value = false
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    // 重新获取列表页数据
    categoryStore.getAttrInfoList(
      categoryStore.category1Id,
      categoryStore.category2Id,
      categoryStore.category3Id
    )
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
// 删除某个属性值
const deleteAttrValue = (row, index: number) => {
  attrParams.attrValueList.splice(index, 1)
}
// 取消保存
const cancelAddAttr = () => {
  addAttrFlag.value = false
}
// 添加属性值按钮点击事件
const addAttrValue = () => {
  console.log('添加属性值')
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //设置flag标识，标识当前时否处于失焦状态
  })
  nextTick(() => {
    // 获取焦点
    inputArr.value[inputArr.value.length - 1].focus()
  })
}
// 输入框失去焦点
const toLook = (row: AttrValue, $index: number) => {
  // 如果当前输入框中没有输入任何内容，不允许失去焦点
  if (row.valueName.trim() == '') {
    // 删除对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    // 提示信息
    ElMessage.warning('当前属性值不能为空')
    return
  }
  // 如果当前输入的属性值和之前的属性值重复，那么不允许添加
  let repeat = attrParams.attrValueList.find((item) => {
    // 将当前元素从数组中剔除
    if (item != row) {
      return row.valueName == item.valueName
    }
  })
  if (repeat) {
    // 删除对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    ElMessage.warning('不允许添加重复的属性值')
  }
  // 将当前的flag置为false
  row.flag = false
}
// 获取焦点
const toEdit = (row: AttrValue, $index: number) => {
  // 将当前的flag置为true
  row.flag = true
  // 让当前点击的元素输入框获取焦点
  nextTick(() => {
    // 当flag变化时，此时页面刚渲染一次，这时获取不到当前输入框的元素，需要使用nextTick，当下一次更新页面时获取input输入框
    inputArr.value[$index].focus()
  })
}
onMounted(() => {
  getC1List()
})
// keep-alive自带的两个钩子函数
onActivated(() => {
  getC1List()
})
onDeactivated(() => {
  // 因为category组件是属性管理和spu管理公共的组件，所以这里在组件销毁时，清空store中的数据
  categoryStore.$reset()
})
</script>
<style lang="scss" scoped></style>
